package com.xm.linxiaogang.network.body

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import java.io.File
import java.io.FileInputStream
import java.io.IOException

/**
 * 上传文件的请求体
 */
class UploadRequestBody(private val file: File, private val callback: UploadCallback?) :
    RequestBody() {

    private val bufferSize = 2048

    override fun contentType(): MediaType? {
        return MediaType.parse("image/*")
    }

    @Throws(IOException::class)
    override fun contentLength(): Long {
        return file.length()
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        val fileLength = file.length()
        val buffer = ByteArray(bufferSize)
        val inputStream = FileInputStream(file)
        var uploaded: Long = 0
        try {
            var read: Int
            while (inputStream.read(buffer).also { read = it } != -1) {
                uploaded += read.toLong()
                sink.write(buffer, 0, read)
                callback?.onProgressUpdate((uploaded * 100 / fileLength).toInt())
            }
            callback?.onCompleted(file)
        } catch (e: Exception) {
            callback?.onUpLoadFail(e)
        } finally {
            inputStream.close()
        }
    }

    interface UploadCallback {
        //上传进度
        fun onProgressUpdate(percentage: Int)

        //上传完成
        fun onCompleted(file: File)

        //上传失败
        fun onUpLoadFail(throwable: Throwable)
    }

}